<script setup>
import { ref, watch } from "vue";

// 引入图标
import { Check, Edit, Delete, Select } from "@element-plus/icons-vue";

const shcedules = ref([
  {
    scheduleId: 1, // 主键
    flightId: 101, // 航班ID
    departureDate: new Date(2024, 10, 20), // 出发日期，注意月份是从0开始的，所以11月是10
    status: 1, // 航班状态
    departureTime: '08:00', // 出发时间
    arrivalDate: new Date(2024, 10, 20), // 到达日期
    arrivalTime: '11:00', // 到达时间
    delayInfo: 0, // 航班延误信息
    departureAirportName: '北京首都国际机场', // 出发机场名称
    arrivalAirportName: '上海浦东国际机场', // 到达机场名称
    flightDistance: 1200, // 航程距离，单位可以是公里
    flightNumber: 'CA1234' // 航班号
  },
  // ...其他航班计划对象
]);

shcedules.value = [];
// 分页查询模型
const pageNo = ref(1);
const pageSize = ref(10);
const total = ref(20); //总条数
const isAsc = ref(true);

// 机场查询模型
const departureAirportName = ref("");
const arrivalAirportName = ref("");
const departureDate = ref(new Date());

const zhCN = 'zh-cn';

const title = ref('');

// 机场模型
const airports = ref([
  {
    airportId: 1, // 主键
    airportCode: 'BJP', // 机场代码
    airportName: '北京', // 机场名称
    cityName: '北京', // 城市名称
  },
]);

import {
  getShceduleListQueryService,
  getAirportListService,
  getTicketQueryListService,
  getSeatQueryListService,
  addTicketService,
  startOrstopTicketService,
  changeScheduleStatusService,

} from "../../api/operation.js";

import { ElMessage } from "element-plus";



const getAirportList = async () => {
  let result = await getAirportListService();
  airports.value = result.data;
};

import { useTokenStore } from "@/src-manager/stores/token.js";

const tokenStore = useTokenStore();


// 判断token是否存在
const token = tokenStore.token;
if (token) {
  getAirportList();
}




const getShceduleListQuery = async () => {

  // 可以选择性的传入参数

  let params = new URLSearchParams();

  if (departureAirportName.value) {
    params.append('departureAirportName', departureAirportName.value);
  }
  if (arrivalAirportName.value) {
    params.append('arrivalAirportName', arrivalAirportName.value);
  }
  if (departureDate.value) {
    params.append('departureDate', formatDate(departureDate.value));
  }


  params.append('pageNo', pageNo.value);
  params.append('pageSize', pageSize.value);
  params.append('isAsc', isAsc.value);


  let result = await getShceduleListQueryService(params);
  total.value = result.data.total;
  shcedules.value = result.data.total === 0 ? [] : result.data.list;

};

const tickets = ref([
  {
    ticketId: 1, // 票证ID
    seatNumber: '', // 座位号
    price: 1, // 座位价格
    departureDate: new Date(), // 出发日期
    departureTime: '', // 出发时间
    arrivalDate: new Date(), // 到达日期
    arrivalTime: '', // 到达时间
    flightNumber: '', // 航班号
    departureAirportName: '', // 出发机场名称
    arrivalAirportName: '' // 到达机场名称
  },

]);

// 票据分页查询模型
const scheduleId = ref(1);
const classId = ref('');
const status = ref(1);

const getTicketQueryList = async () => {
  let params = new URLSearchParams();
  params.append('pageNo', pageNo.value);
  params.append('pageSize', pageSize.value);
  params.append('scheduleId', scheduleId.value);
  params.append('classId', classId.value);
  params.append('status', status.value);

  let result = await getTicketQueryListService(params);
  total.value = result.data.total;

  if (result.data.total === 0) {
    tickets.value = [];
    ElMessage.error('没有数据');
    title.value = '启用票据';
    return;
  }




  tickets.value = result.data.list;

  title.value = '禁用票据';




};








const onScheduleSizeChange = (size) => {
  pageSize.value = size;
  getShceduleListQuery();

}


const onSchedulePageNoChange = (num) => {
  pageNo.value = num;
  getShceduleListQuery();
}


//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  getTicketQueryList();
};

//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNo.value = num;
  getTicketQueryList();
};

// 控制抽屉显示
const isVisibleDrawer = ref(false);

const showCheckTicketDrawer = (row) => {
  scheduleId.value = row.scheduleId;
  isVisibleDrawer.value = true;
};





// 调用查询接口
const rules = {
  departureAirportName: [
    { required: true, message: "请输入出发地机场名称", trigger: "blur" },
  ],
  arrivalAirportName: [
    { required: true, message: "请输入目的地机场名称", trigger: "blur" },
  ],
};







// 多选
const ticketIds = ref([]);

const handleSelectionChange = (selection) => {


  ticketIds.value = selection.map((item) => item.ticketId);

  console.log(ticketIds.value);
}


const formatDate = (value) => {
  if (!value) return '';
  const date = new Date(value);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}/${month}/${day}`;
};

const formatTime = (time) => {
  if (!time) return '';
  return time.toString().padStart(5, '0');
};

const formatStatus = (status) => {
  const statusMap = {
    0: '禁用',
    1: '可购票',
    2: '已延迟',
    3: '已出发',
    4: '已到达',
  };
  return statusMap[status] || '未知状态';
};


const formatTicketStatus = (status) => {
  const statusMap = {
    1: '可购票',
    2: '待支付',
    3: '已完成',
    5: '已支付'

  };
  return statusMap[status] || '未知状态';
};


const isAddTicketDialogVisible = ref(false);

const seats = ref([
  {
    seatId: null,
    airplaneId: null,
    seatNumber: '',
    status: null,
  }
]);

seats.value = [];

const getSeatQueryList = async () => {

  let params = new URLSearchParams();
  params.append('pageNo', pageNo.value);
  params.append('pageSize', pageSize.value);
  params.append('isAsc', isAsc.value);
  params.append('classId', classId.value);
  params.append('scheduleId', scheduleId.value);
  let result = await getSeatQueryListService(params);
  total.value = result.data.total;
  seats.value = result.data.list;
}


const onSeatSizeChange = (size) => {
  pageSize.value = size;

  getSeatQueryList();
}

const onSeatPageNoChange = (num) => {
  pageNo.value = num;
  getSeatQueryList();

}



const showAddTicketDialog = (row) => {

  scheduleId.value = row.scheduleId;
  isAddTicketDialogVisible.value = true;

}


const addTicket = async () => {

  let params = new URLSearchParams();
  params.append('scheduleId', scheduleId.value)

  let result = await addTicketService(params);

  if (result.code === 200) {
    ElMessage.success('新增票据成功');
    isAddTicketDialogVisible.value = false;
    getShceduleListQuery();
  }

}



const startOrstopTicket = async () => {

  let params = new URLSearchParams();
  params.append('scheduleId', scheduleId.value);


  let result = await startOrstopTicketService(params);



  if (result.code === 200) {
    if (result.data === 1) {
      title.value = '禁用票据';
    } else if (result.data === 0) {
      title.value = '启用票据';
    }

    getTicketQueryList();

  }




}


const ScheduleStatus = ref('');


const changeScheduleStatus = async (shceduleId) => {

  let result = await changeScheduleStatusService(shceduleId, ScheduleStatus.value);

  if (result.code === 200) {
    ElMessage.success('状态改变成功');
    ScheduleStatus.value = '';
    getShceduleListQuery();
  }

}











</script>

<template>
  <!-- 展示条件筛选班次结果页面 -->
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>班次查询</span>
      </div>
    </template>

    <el-form inline>
      <el-row>
        <el-form-item label="出发机场名称">
          <el-select v-model="departureAirportName" placeholder="出发机场名称" style="width:200px">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="airport in airports" :key="airport.airportId" :label="airport.airportName"
              :value="airport.airportName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目的机场名称">
          <el-select v-model="arrivalAirportName" placeholder="目的机场名称" style="width:200px">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="airport in airports" :key="airport.airportId" :label="airport.airportName"
              :value="airport.airportName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="出发日期">
          <el-date-picker v-model="departureDate" type="date" placeholder="选择出发日期" lang="zh-CN" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getShceduleListQuery()" layout="right">查询</el-button>
          <el-button type="primary" @click="
            departureAirportName = '';
          arrivalAirportName = '';
          departureDate = new Date();
          pageNo = 1;
          pageSize = 10
            ">
            重置
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-table :data="shcedules" style="width: 100%">
      <el-table-column label="序号" width="70" prop="scheduleId"></el-table-column>
      <!-- 航班ID列 -->
      <el-table-column label="航班ID" prop="flightId"></el-table-column>
      <!-- 出发日期列 -->
      <el-table-column label="出发日期" prop="departureDate">
        <template #default="{ row }">
          {{ formatDate(row.departureDate) }}
        </template>
      </el-table-column>

      <!-- 航班状态列 -->
      <el-table-column label="航班状态" prop="status">
        <template #default="{ row }">
          {{ formatStatus(row.status) }}
        </template>
      </el-table-column>

      <!-- 出发时间列 -->
      <el-table-column label="出发时间" prop="departureTime">
        <template #default="{ row }">
          {{ formatTime(row.departureTime) }}
        </template>
      </el-table-column>

      <!-- 到达日期列 -->
      <el-table-column label="到达日期" prop="arrivalDate">
        <template #default="{ row }">
          {{ formatDate(row.arrivalDate) }}
        </template>
      </el-table-column>

      <!-- 到达时间列 -->
      <el-table-column label="到达时间" prop="arrivalTime">
        <template #default="{ row }">
          {{ formatTime(row.arrivalTime) }}
        </template>
      </el-table-column>



      <!-- 出发机场名称列 -->
      <el-table-column label="出发机场" prop="departureAirportName"></el-table-column>

      <!-- 到达机场名称列 -->
      <el-table-column label="到达机场" prop="arrivalAirportName"></el-table-column>

      <!-- 航程距离列 -->
      <el-table-column label="航程距离" prop="flightDistance"></el-table-column>

      <!-- 航班号列 -->
      <el-table-column label="航班号" prop="flightNumber"></el-table-column>

      <!-- 操作列 -->
      <el-table-column label="票据查看">
        <template #default="{ row }">
          <el-button :icon="Check" circle plain type="primary" @click="showCheckTicketDrawer(row)">
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="票据新增">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showAddTicketDialog(row)">
          </el-button>
        </template>
      </el-table-column>


      <el-table-column label="状态改变">
        <template #default="{ row }">

          <el-select v-model="ScheduleStatus" placeholder="选择座位等级" @change="changeScheduleStatus(row.scheduleId)">
            <el-option label="可选票" value="1"></el-option>
            <el-option label="已延迟" value="2"></el-option>
            <el-option label="已出发" value="3"></el-option>
            <el-option label="已到达" value="4"></el-option>
          </el-select>
        </template>
      </el-table-column>



      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
  </el-card>

  <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
    layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onScheduleSizeChange"
    @current-change="onSchedulePageNoChange" style="margin-top: 20px; justify-content: flex-end"></el-pagination>



  <!-- 抽屉组件 -->

  <el-drawer v-model="isVisibleDrawer" direction="rtl" size="70%">
    <el-form :rules="rules" ref="form" label-width="120px" class="drawer-form">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="选择座位等级">
            <el-select v-model="classId" placeholder="选择座位等级" style="width: 100%;" @change="getTicketQueryList()">
              <el-option label="头等舱" value="1"></el-option>
              <el-option label="公务舱" value="2"></el-option>
              <el-option label="经济舱" value="3"></el-option>
            </el-select>
          </el-form-item>

          <!-- 介绍三种座位等级 -->
          <el-form-item label="三类座位的区别">
            <p>头等舱(First Class)通常位于飞机的最前部，提供最豪华的设施和服务。舱位代码为F，代表头等舱公布价。
              公务舱(Business Class)紧挨着头等舱，提供比经济舱更舒适的座椅和额外的服务。舱位代码为C，代表公务舱公布价。
              经济舱(Economy Class)是飞机上最常见的舱位，座位位于飞机的中部到尾部，占机身的大部分空间。舱位代码为Y，代表普通舱(经济舱)公布价。</p>
          </el-form-item>


          <el-form-item style="width: 100%;">
            <el-button type="primary" @click="startOrstopTicket()">{{ title }}</el-button>
          </el-form-item>


        </el-col>


        <el-col :span="12">
          <el-form-item stronge label="出发日期">
            {{ formatDate(tickets[0].departureDate)}}
          </el-form-item>
          <el-form-item label="出发时间">
            {{ tickets[0].departureTime }}
          </el-form-item>
          <el-form-item label="到达日期">
            {{ formatDate(tickets[0].arrivalDate) }}
          </el-form-item>
          <el-form-item label="到达时间">
            {{ tickets[0].arrivalTime }}
          </el-form-item>
          <el-form-item label="航班号">
            {{ tickets[0].flightNumber }}
          </el-form-item>
          <el-form-item label="出发机场">
            {{ tickets[0].departureAirportName }}
          </el-form-item>
          <el-form-item label="到达机场">
            {{ tickets[0].arrivalAirportName }}
          </el-form-item>
        </el-col>


      </el-row>

    </el-form>

    <el-table :data="tickets" style="width: 100%; margin-top: 20px;" @selection-change="handleSelectionChange"
      ref="multipleTable">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="ticketId" label="票证ID" width="180"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          {{ formatTicketStatus(row.status) }}
        </template>
      </el-table-column>
      <el-table-column prop="seatNumber" label="座位号" width="180"></el-table-column>
      <el-table-column prop="price" label="价格" width="180"></el-table-column>

      <!-- 操作列 -->
      <!-- <el-table-column label="操作">  
        <template #default="{ row }">

        </template>
      </el-table-column> -->


    </el-table>


    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
      @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"></el-pagination>
  </el-drawer>


  <!-- 新增票据弹窗 -->


  <el-dialog v-model="isAddTicketDialogVisible" width="60%">

    <el-form label="班次信息">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="班次id" style="width: 100%;">
            <strong>{{ scheduleId }}</strong>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="选择座位等级" style="width: 100%;">
            <el-select v-model="classId" placeholder="选择座位等级" style="width: 100%;" @change="getSeatQueryList()">
              <el-option label="头等舱" value="1"></el-option>
              <el-option label="公务舱" value="2"></el-option>
              <el-option label="经济舱" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item style="width: 100%;">
            <el-button type="primary" @click="addTicket()">确认新增票据</el-button>
          </el-form-item>

        </el-col>
      </el-row>
    </el-form>


    <!-- 座位展示表格 -->
    <el-table :data="seats" style="width: 100%; margin-top: 20px;">

      <el-table-column prop="seatId" label="序号" width="180"></el-table-column>
      <el-table-column prop="airplaneId" label="航班号" width="180"></el-table-column>
      <el-table-column prop="seatNumber" label="座位号" width="180"></el-table-column>
      <el-table-column prop="status" label="状态" width="180"></el-table-column>

    </el-table>

    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSeatSizeChange"
      @current-change="onSeatPageNoChange" style="margin-top: 20px; justify-content: flex-end"></el-pagination>

  </el-dialog>




</template>

<style lang="scss" scoped>
.page-container {
  min-height: 80%;
  box-sizing: border-box;
  padding: 20px;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
  }
}

/* 抽屉样式 */
.drawer-form {
  padding: 20px;

  .el-form-item {
    margin-bottom: 20px;
  }

  .button-row {
    margin-top: 20px;
  }
}

.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
</style>